<?php

namespace App\Services;

use App\Models\HallDomain;
use common\enum\CommonEnum;
use common\utils\RedisKeys;
use common\utils\SysCode;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class DomainManageService
{
    /**
     * 厅主名称列表
     * @return mixed
     */
    public static function domainList($values)
    {
        $select = ['a.id', 'a.hall_id', 'a.domain', 'a.status', 'a.created_at', 'a.updated_at', 'b.company_name as hall_name', 'b.admin_name'];
        $query  = DB::table('hall_domain as a')
            ->leftJoin('hall as b', 'b.id', '=', 'a.hall_id')
            ->select($select)
            ->orderBy('a.id', 'desc');
        if (!empty($values['hall_id'])) {
            $query->where(['a.hall_id' => $values['hall_id']]);
        }
        if (!empty($values['status']) || isset($values['status'])) {
            $query->where(['a.status' => $values['status']]);
        }
        $page = $values['page'] ?? CommonEnum::PAGE_DEFAULT;
        $size = $values['page_size'] ?? CommonEnum::PAGE_SIZE_TWENTY;
        return get_page_data($query, $page, $size);
    }


    /**
     * 添加域名
     * @param $values
     * @return mixed
     * @throws \App\Exceptions\CustomException
     */
    public static function addDomain($values)
    {
        $domain = explode(';', $values['domain']);
        $list   = HallDomain::whereIn('domain', $domain)->get()->toArray();
        if (!empty($list)) {
            $domains = array_column($list, 'domain');
            error_exit(SysCode::HALL_DOMAIN_EXIST, ['domains' => implode(',', $domains)]);
        }
        $insert['hall_id'] = $values['hall_id'];
        $insert['status']  = CommonEnum::ENABLED;
        foreach ($domain as $val) {
            self::getDomain($val);
            $insert['domain'] = $val;
            $result           = HallDomain::insertGetId($insert);
        }
        if (!$result) {
            error_exit(SysCode::FAILED);
        }
        return $result;
    }

    public static function getDomain($domain)
    {
        $result = preg_match("/^(?=^.{3,255}$)[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})$/", $domain);
        if (!$result) {
            error_exit(SysCode::HALL_DOMAIN_ERROR, ['domain' => $domain]);
        }
    }

    /**
     * 域名启/停
     * @param $id
     * @param $status
     * @return mixed
     */
    public static function updateStatus($id, $status)
    {
        $result = HallDomain::where(['id' => $id])->update($status);
        if (!$result) {
            error_exit(SysCode::FAILED);
        }
        if ((int)$status['status'] === CommonEnum::DISABLE) {
            self::delRedisKey($id);
        }
        return $result;
    }

    /**
     * 删除redis域名缓存
     * @param $id
     */
    public static function delRedisKey($id)
    {
        $domain = HallDomain::where(['id' => $id])->pluck('domain');
        $redis  = Redis::connection();
        $value  = $redis->get(RedisKeys::DOMAIN_KEY . $domain['0']);
        if ($value != null) {
            $redis->del(RedisKeys::DOMAIN_KEY . $domain['0']);
        }
    }

    /**
     * 修改域名
     * @param $id
     * @param $domain
     * @return mixed
     */
    public static function updateDomain($id, $domain)
    {
        $list = HallDomain::where(['domain' => $domain['domain']])->whereRaw('id !='. $id)->first();
        if(!empty($list)){
            error_exit(SysCode::HALL_DOMAIN_EXIST, ['domains' => $list['domain']]);
        }
        $data = HallDomain::where(['id' => $id])->pluck('domain');
        self::getDomain($domain['domain']);
        $result = HallDomain::where(['id' => $id])->update($domain);
        if (!$result) {
            error_exit(SysCode::FAILED);
        }
        $redis  = Redis::connection();
        $value  = $redis->get(RedisKeys::DOMAIN_KEY . $data['0']);
        if ($value != null) {
            $redis->del(RedisKeys::DOMAIN_KEY . $data['0']);
        }
        return $result;
    }
}
